// 子组件可以通过 ref 给父组件供应数据和函数，父组件可以在事件处理中使用

import React, { useRef, useImperativeHandle, useCallback } from 'react';

const Component = React.forwardRef((props: any, ref: any) => {

  const inputRef = useRef<any>();

  // 向上暴露子组件数据和方法
  useImperativeHandle(ref, () => ({
    ...ref.current,
    ['focus' + props.id]: () => {
      inputRef.current.focus();
    }
  }), []);

  return (
    <input ref={inputRef} />
  );
});

export default function CustomizedRef() {
  const ref = useRef<any>();
  const handleButtonClick = useCallback(() => {
    console.log(ref);
    ref.current.focus2();
  }, []);
  return (
    <div>
      <div><button onClick={handleButtonClick}>focus component below</button></div>
      <Component ref={ref} id="1" />
      <Component ref={ref} id="2" />
    </div>
  );
}
